﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace Derbster.Peer
{
    public static class MessageQueueExtensions
    {
        public static async Task<Message> RecieveAsync(this MessageQueue messageQueue)
        {
            return await messageQueue.RecieveAsync(TimeSpan.FromMinutes(10), null);
        }

        public static async Task<Message> RecieveAsync(this MessageQueue messageQueue, TimeSpan timeout)
        {
            return await messageQueue.RecieveAsync(timeout, null);
        }

        public static async Task<Message> RecieveAsync(this MessageQueue messageQueue, TimeSpan timeout, object stateObject)
        {
            return await Task.Factory.FromAsync(
                (callback, o) => messageQueue.BeginReceive(timeout, o, callback),
                (result) => messageQueue.EndReceive(result),
                stateObject).ConfigureAwait(false);
        }

        public static void SetFormatter<T>(this MessageQueue mq)
        {
            mq.Formatter = new XmlMessageFormatter(new[] { typeof(T) });
        }
    }
}
